package mysql

import (
	"GoWebBluebell/models"
	"strings"

	"github.com/jmoiron/sqlx"
)

// CreatePost 创建帖子
func CreatePost(p *models.Post) (err error) {
	sqlStr := `insert into post(
	post_id, title, content, author_id, community_id)
	values (?, ?, ?, ?, ?)
	`
	_, err = db.Exec(sqlStr, p.ID, p.Title, p.Content, p.AuthorID, p.CommunityID)
	return err
}

// GetPostByID 根据id查询单个帖子数据
func GetPostByID(pid int64) (post *models.Post, err error) {
	post = new(models.Post)
	sqlStr := `select 
	post_id, title, content, author_id, community_id, create_time 
	from post 
	ORDER BY create_time
	DESC
	where post_id = ?`
	// 以 create_time 排序 DESC 降序
	err = db.Get(post, sqlStr, pid)
	return
}

// GetPostList 查询帖子列表函数
func GetPostList(page, size int64) (posts []*models.Post, err error) {
	sqlStr := `select 
	post_id, title, content, author_id, community_id, create_time
	from post
	limit ?,?` //第一个问号表示从哪开始, 第二个问号表示取多少条
	posts = make([]*models.Post, 0, 2)
	err = db.Select(&posts, sqlStr, (page-1)*size, size)
	return
}

// 根据给定的id列表查询帖子数据
func GetPostListByIDs(pids []string) (postList []*models.Post, err error) {
	sqlStr := `select post_id, title, content, author_id, community_id, create_time
	from post
	where post_id in (?)
	order by FIND_IN_SET(post_id, ?)`
	//FIND_IN_SET mysql内置的函数, 根据指定的顺序排序查询结果
	query, args, err := sqlx.In(sqlStr, pids, strings.Join(pids, ","))
	if err != nil {
		return nil, err
	}

	// sqlx.In 返回带 `?` bindvar的查询语句, 我们使用Rebind()重新绑定。
	// 重新生成对应数据库的查询语句（如PostgreSQL 用 `$1`, `$2` bindvar）
	query = db.Rebind(query) // 重新绑定

	err = db.Select(&postList, query, args...) //...
	return
}
